package com.ruoyi.app.controller;

import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.wechat.service.WechatMiniappService;
import com.ruoyi.wechat.vo.WeChatMiniappLoginVo;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.app.service.AppLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.wechat.service.WechatMpService;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Set;

/**
 * description: APP默认登录控制层
 * date: 2023年04月11日 9:03
 * author: tmac-1
 * version: 1.0
 */
@RestController
@RequestMapping("/app/login/")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class AppLoginController {
    private final AppLoginService appLoginService;
    private final SysPermissionService permissionService;
    private final WechatMpService wechatMpService;
    private final WechatMiniappService wechatMiniappService;

    @ApiOperation("账号密码登录")
    @PostMapping("common/login")
    public AjaxResult login(@RequestBody LoginBody entity) {
        return AjaxResult.success("登录成功", appLoginService.login(entity));
    }

    @ApiOperation("微信公众号授权登录")
    @GetMapping("common/weChatMpLogin")
    @RepeatSubmit
    public AjaxResult weChatMpLogin() {
        return AjaxResult.success("登录成功", wechatMpService.buildAuthorizationUrl());
    }

    @ApiOperation("微信公众号登录回调")
    @RequestMapping("common/weChatMpCallback")
    public void weChatMpCallback() {
        wechatMpService.callback();
    }

    @ApiOperation("微信小程序授权登录")
    @PostMapping("common/weChatMiniappLogin")
    @RepeatSubmit
    public AjaxResult weChatMiniappLogin(@RequestBody WeChatMiniappLoginVo weChatMiniappLoginVo) {
        if (StringUtils.isBlank(weChatMiniappLoginVo.getCode())) {
            return AjaxResult.error("code不能为空");
        }
        String token = wechatMiniappService.login(weChatMiniappLoginVo);
        AjaxResult ajax = AjaxResult.success();
        return ajax.put(Constants.TOKEN, token);
    }

    @ApiOperation("获取用户信息")
    @GetMapping("getInfo")
    public AjaxResult getInfo() {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }
}
